import React, { useEffect, useState } from "react";

//请求引入
import {
  getCityListRequest,
  getHospitalListRequest,
  getProvinceListRequest,
  statusChangeRequest,
} from "@api/hospital/hospitalList";

//组件引入
import {
  Form,
  Card,
  Button,
  Input,
  Select,
  Table,
  Row,
  Col,
  message,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";

//类型引入
import {
  getHosListSearchParamsType,
  hospitalListContentType,
  getProvinceListItemType,
  hospitalListItemType,
} from "@/api/hospital/model/hospitalListTypes";
import { useNavigate } from "react-router-dom";

//定义等级和详细地址组成对象的类型
interface contentParamsType {
  hostypeString: string;
  fullAddress: string;
}

//医院列表组件
export default function HospitalList() {
  const navigate = useNavigate();
  //将Select组件里的Option实例化
  const { Option } = Select;
  const [form] = Form.useForm();

  const [hospitalList, setHospitalList] = useState<hospitalListContentType>([]);
  //设置控制进度条的状态
  const [isLoading, setIsLoading] = useState(false);
  //设置当前的页码的状态
  const [page, setPage] = useState(1);
  //设置每页数据的个数的状态
  const [limit, setLimit] = useState(3);
  //设置数据的总个数的状态
  const [total, setTotal] = useState(0);
  //搜索的参数状态，后续通过表单改变状态
  const [searchParams, setSearchParams] =
    useState<getHosListSearchParamsType>();
  //设置省份的状态
  const [provinceList, setProvinceList] = useState<getProvinceListItemType>([]);
  //设置市级的状态
  const [cityList, setCityList] = useState<getProvinceListItemType>([]);
  //设置区级的状态
  const [districtList, setDistrictList] = useState<getProvinceListItemType>([]);
  //设置医院类型的状态
  const [hospitalType, setHospitalType] = useState<getProvinceListItemType>([]);
  //自定义渲染的状态，需要页面渲染的时候改变
  const [reRender, setReRender] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    const getHospitalList = async () => {
      //数据请求
      const result = await getHospitalListRequest(page, limit, searchParams);
      //将请求回来的数据添加到状态里
      setHospitalList(result.content);
      //数据总个数
      setTotal(result.totalElements);
      setIsLoading(false);
    };
    getHospitalList();
  }, [HospitalList, searchParams, page, limit, reRender]);

  useEffect(() => {
    //获取省份的请求
    const getProvince = async () => {
      const result = await getProvinceListRequest();
      //将获取到的省份列表设置到状态
      setProvinceList(result);
    };
    getProvince();
  }, []);

  useEffect(() => {
    const getHosType = async () => {
      const result = await getCityListRequest("10000");
      setHospitalType(result);
    };
    getHosType();
  }, []);

  //事件回调函数
  //1.选择省份的时候事件回调函数
  const provinceChangeHandle = async (value: string) => {
    const result = await getCityListRequest(value);
    setCityList(result);
    //每次请求，将下级选项清除，属性名对应name
    form.setFieldsValue({ city: null, district: null });
    //并将区级数据重置
    setDistrictList([]);
  };
  //2.选择城市的时候事件回调函数
  const districtChangeHandle = async (value: string) => {
    const result = await getCityListRequest(value);
    //区级的数据设置
    setDistrictList(result);
    //每次请求，将下级选项清除，属性名对应name
    form.setFieldsValue({ district: null });
  };
  //3.查询表单的提交事件，表单改变search状态，发请求重新渲染
  const formSubmitHandle = (fieldValue: getHosListSearchParamsType) => {
    // console.log(fieldValue);
    setSearchParams(fieldValue);
  };
  //4.点击查询表单的清空按钮
  const clearSearchHandle = () => {
    setSearchParams({});
  };
  //5.点击查看按钮事件回调函数
  const hospitalShowHandle = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalshow/${id}`);
    };
  };
  //6.点击上下线按钮事件回调函数
  const statusChangeHandle = (id: string, status: 0 | 1) => {
    return async () => {
      await statusChangeRequest(id, status);
      message.success(status ? "上线成功" : "下线成功");
      setReRender(!reRender);
    };
  };
  //7.点击排班按钮事件回调函数
  const hospitalScheduleHandle = (hoscode: string) => {
    return async () => {
      navigate(`/syt/hospital/hospitalSchedule/${hoscode}`);
    };
  };
  //表格的字段
  const columns = [
    {
      title: "#",
      dataIndex: "index",
      width: 50,
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院Logo",
      dataIndex: "logoData",
      width: 135,
      render(logoData: string) {
        return (
          <img
            style={{ width: 100 }}
            src={`data:image/jpeg;base64,${logoData}`}
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "等级",
      dataIndex: "param",
      render(param: contentParamsType) {
        return param.hostypeString;
      },
    },
    {
      title: "详细地址",
      dataIndex: "param",
      render(param: contentParamsType) {
        return param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(status: 0 | 1) {
        return status ? "上线" : "下线";
      },
    },
    {
      title: "创建事件",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      dataIndex: "Buttons",
      fixed: "right" as "right",
      width: 120,
      render(_: any, data: hospitalListItemType) {
        const { id, hoscode } = data;
        return (
          <div>
            {/* 查看按钮跳转 */}
            <Button type="primary" onClick={hospitalShowHandle(id)}>
              查看
            </Button>
            <Button type="primary" onClick={hospitalScheduleHandle(hoscode)}>
              排班
            </Button>
            <Button
              type="primary"
              onClick={statusChangeHandle(id, !data.status ? 1 : 0)}
            >
              {!data.status ? "上线" : "下线"}
            </Button>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <Card>
        <Form
          name="basic"
          // wrapperCol={{ span: 30 }}
          autoComplete="off"
          form={form}
          onFinish={formSubmitHandle}
        >
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请选择省"
                  allowClear
                  onChange={provinceChangeHandle}
                >
                  {provinceList.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={districtChangeHandle}
                >
                  {cityList.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择区" allowClear>
                  {districtList.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                  {hospitalType.map((item) => {
                    return (
                      <Option value={item.value} key={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Option value={1}>上线</Option>
                  <Option value={0}>下线</Option>
                </Select>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item>
                <Button
                  type="default"
                  htmlType="reset"
                  onClick={clearSearchHandle}
                >
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Table
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1500 }}
          rowKey="id"
          bordered
          loading={isLoading}
          //给表格的配置页码，通过对象配置
          pagination={{
            //当前页码
            current: page,
            //数据的数量
            total,
            //每页多少条
            pageSize: limit,
            //展示更改每页条数的选项（默认total大于50条的时候开启）
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `共${total}条数据`;
            },
            onChange(page, pageSize) {
              setPage(page);
              setLimit(pageSize);
            },
          }}
        />
      </Card>
    </div>
  );
}
